<template>
  <view class="page-container">
    <!-- 顶部 -->
    <GlobalTopBar ref="topBarRef" :isLeft="true">
      <template #title>登录/注册</template>
    </GlobalTopBar>
    <!-- 内容 -->
    <image
      class="logo"
      :src="`${store.imgDomain}login2_logo.jpg`"
      mode="scaleToFill"
    />
    <view class="hytext">欢迎登录/注册</view>

    <view class="page_content">
      <!-- 手机号 -->
      <view class="phone">
        <view class="tlef">
          <image
            class="phoneimg"
            :src="`${store.imgDomain}login2_phone.jpg`"
            mode="scaleToFill"
          />
        </view>
        <input
          v-model="phone"
          class="uni-input"
          type="number"
          focus
          maxlength="11"
          placeholder="请输入手机号"
        />
      </view>
      <!-- 验证码 -->
      <view class="phone yzm">
        <view class="tlef">
          <image
            class="phoneimg"
            :src="`${store.imgDomain}login2_aq.jpg`"
            mode="scaleToFill"
          />
        </view>
        <input
          v-model="sms_code"
          class="uni-input"
          type="number"
          placeholder="请输入验证码"
          maxlength="10"
        />
        <view
          class="yzmtext"
          :class="{ ac: yzmText != '获取验证码' }"
          @click="sendSmsCode"
          >{{ yzmText }}</view
        >
      </view>
      <button class="btn" @click="loginFun">登录 / 注册</button>
      <label class="radio" @click="radiovalue = !radiovalue"
        ><radio
          style="transform: scale(0.8)"
          color="#007AF0"
          value="1"
          :checked="radiovalue"
        /><text
          >我已阅读并同意
          <text
            style="color: #3475e0"
            @click.stop="
              store.to(
                '/pages/public/agreement?url=wxapp/login/getUserAgreement',
              )
            "
            >《用户协议》</text
          >和
          <text
            style="color: #3475e0"
            @click.stop="
              store.to(
                '/pages/public/agreement?url=wxapp/login/getPrivacyPolicy',
              )
            "
            >《隐私条款》</text
          ></text
        ></label
      >
      <y-drawer
        ref="drawerRef"
        :borderRadius="20"
        :maskClosable="true"
        :length="700"
      >
        <nameimg @hadeorname="gethadeornameFun" />
      </y-drawer>
    </view>
  </view>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';
import { useCounterStore } from '@/store';
import request from '@/utils/request';
import { validatePhone } from '@/utils/validate';
import nameimg from '../../components/nameimg.vue';

const title = ref('hello');
const radiovalue = ref(false);
const nickorhide = ref(false);
const drawerRef = ref(null);
const store = useCounterStore();
const phone = ref('');
const sms_code = ref('');
const yzmText = ref('获取验证码');

// 获取新用户头像昵称
const gethadeornameFun = (data) => {
  store.nick_name = data.nickname;
  store.headimg = data.headimg;
  doRegister();
};

// 发送短信验证码接口（小程序手动登录
const sendSmsCode = async () => {
  if (yzmText.value !== '获取验证码') return;
  if (!radiovalue.value) {
    uni.showToast({
      title: '请先阅读并同意《用户协议》和《隐私条款》',
      icon: 'none',
    });
    return;
  }
  if (validatePhone(phone.value)) {
    const data = await request('wxapp/login/sendSmsCode', {
      mobile: phone.value,
    });
    let num = 60;
    yzmText.value = 60;
    const timer = setInterval(() => {
      num--;
      yzmText.value = num;
      if (num === 0) {
        clearInterval(timer);
        yzmText.value = '获取验证码';
      }
    }, 1000);
  } else {
    uni.showToast({
      title: `请填写正确的手机号`,
      icon: 'none',
    });
  }
};

// 登录
const loginFun = async () => {
  if (!phone.value) {
    uni.showToast({
      title: `请填写正确的手机号`,
      icon: 'none',
    });
    return;
  }
  if (!sms_code.value) {
    uni.showToast({
      title: `请填写验证码`,
      icon: 'none',
    });
    return;
  }
  await uni.login({
    provider: 'weixin', //使用微信登录
    success: async function (res) {
      if (store.open_id) {
        doLogin();
        return;
      }
      await getOpenId(res.code);
    },
  });
};

// 通过code获取微信用户Openid
const getOpenId = async (code) => {
  const data = await request('wxapp/login/getOpenId', { code });
  store.open_id = data.openid;
  uni.setStorageSync('open_id', store.open_id);
  doLogin();
};

// 登录
const doLogin = async () => {
  const datas = {
    login_type: 2,
    phone: phone.value,
    sms_code: sms_code.value,
  };
  request('wxapp/login/doLogin', datas)
    .then((res) => {
      store.is_type = 1;
      uni.setStorageSync('is_type', 1);
      store.userInfo = res;
      uni.redirectTo({
        url: '/pages/home/index',
      });
    })
    .catch((err) => {
      if (err.data.msg === '当前账号不存在,请注册') {
        drawerRef.value.open();
      } else if (err.data.msg === '账号已被禁用') {
        uni.showToast({
          title: '您的账号已被禁用，请联系客服处理',
          icon: 'none',
        });
      }
    })
    .finally(() => {
      store.phone = phone.value;
      uni.setStorageSync('phone', phone.value);
    });
};
// 个人会员注册
const doRegister = async () => {
  const datas = {
    register_type: 2,
    phone: phone.value,
    nick_name: store.nick_name,
    headimg: store.headimg,
    sms_code: sms_code.value,
  };
  const data = await request('wxapp/login/doRegister', datas);
  store.is_type = 1;
  uni.setStorageSync('is_type', 1);
  store.userInfo = data;
  uni.redirectTo({
    url: '/pages/home/index',
  });
  console.log('注册成功', data);
};
</script>
<style scoped lang="scss">
.page-container {
  position: relative;
  justify-content: center;
  background-color: #fff;
  .page_image {
    width: 750rpx;
    height: 502rpx;
  }
}
.page_content {
  padding: 126rpx 63rpx 0;
  box-sizing: border-box;
  background-color: #fff;
}
.btn {
  height: 90rpx;
  line-height: 90rpx;
  color: #fff;
  background-color: #007ef1;
  border-radius: 45rpx;
  font-size: 30rpx;
  text-align: center;
}
.radio {
  margin-top: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  text {
    color: $uni-text-color-grey;
    font-size: 24rpx;
  }
}

.qttext {
  position: relative;
  width: max-content;
  margin: 160rpx auto 25rpx;
  color: $uni-text-color-grey;
  font-size: 24rpx;
  padding: 0 15rpx;
  &::after {
    content: ' ';
    position: absolute;
    top: 50%;
    left: -40rpx;
    transform: translateY(-50%);
    width: 40rpx;
    height: 1rpx;
    background-color: #0086f2;
  }
  &::before {
    content: ' ';
    position: absolute;
    top: 50%;
    right: -40rpx;
    transform: translateY(-50%);
    width: 40rpx;
    height: 1rpx;
    background-color: #0086f2;
  }
}
.login_iphone {
  display: block;
  margin: 0 auto;
  width: 89rpx;
  height: 89rpx;
}
.logo {
  display: block;
  width: 282rpx;
  height: 108rpx;
  display: block;
  margin: 100rpx auto 20rpx;
}
.hytext {
  text-align: center;
  font-size: 36rpx;
  margin-bottom: 100rpx;
}
.tlef {
  width: 40rpx;
  display: flex;
  justify-content: center;
}
.phone {
  box-sizing: border-box;
  padding: 0 34rpx;
  display: flex;
  align-items: center;
  border-bottom: 1rpx solid #aad3ff;
  margin-bottom: 20rpx;
  .phoneimg {
    width: 30rpx;
    height: 42rpx;
  }
  .uni-input {
    flex: 1;
    height: 90rpx;
    box-sizing: border-box;
    padding-left: 20rpx;
  }
}
.yzm {
  .phoneimg {
    width: 38rpx;
    height: 44rpx;
  }
  .yzmtext {
    position: relative;
    width: 30%;
    text-align: center;
    line-height: 90rpx;
    font-size: 30rpx;
    color: #0185f2;
    &.ac {
      color: $uni-text-color-grey;
    }
    &::after {
      content: ' ';
      position: absolute;
      top: 50%;
      left: -20rpx;
      width: 1rpx;
      height: 44rpx;
      transform: translateY(-50%);
      background-color: #aad3ff;
    }
  }
}
</style>
